package com.wyz.jdk7;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {
    /**
     *  要使用ForkJoin框架就需要创建一个forkJoin任务，
     *  forkjoin 框架提供两个子类。
     *      有返回值的子类 RecursiveTask
     *      没有返回值的子类：RecursiveAction
     * @param args
     */
    public static void main(String[] args) throws Throwable {
        SumTask sumTask = new SumTask(1, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> submit = forkJoinPool.submit(sumTask);
        //是否发生异常
        if (submit.isCompletedAbnormally()) {
            //抛出异常
            throw submit.getException();

        }
        //正常执行 获取结果
        System.out.println("获取结果" + submit.get());
    }



    public static class SumTask extends RecursiveTask<Long>{

        //定义任务处理的阈值
        private static final int THRESHOLD = 10;
        /**
         *  起始值
         */
        private int start;
        /**
         *  结束值
         */
        private int end;

        public SumTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            long sum = 0;
            int val = end - start;
            if (val > THRESHOLD ){
                //进行拆任务
                int middle = val / 2 + start;
                SumTask leftTask = new SumTask(start, middle);
                SumTask rightTask = new SumTask(middle+1, end);
                leftTask.fork();
                rightTask.fork();
                Long lef = leftTask.join();
                Long rig = rightTask.join();
                sum = rig + lef;
            }else{
                for (int i = start; i <= end; i++) {
                    sum += i;
                }
            }
            return sum;
        }
    }

}